package com.pspaceplus.driver.bacnetdemo.util;

import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.RemoteDevice;
import com.serotonin.bacnet4j.exception.BACnetException;
import com.serotonin.bacnet4j.npdu.ip.IpNetwork;
import com.serotonin.bacnet4j.npdu.ip.IpNetworkBuilder;
import com.serotonin.bacnet4j.service.acknowledgement.ReadPropertyAck;
import com.serotonin.bacnet4j.service.confirmed.ReadPropertyRequest;
import com.serotonin.bacnet4j.transport.DefaultTransport;
import com.serotonin.bacnet4j.transport.Transport;
import com.serotonin.bacnet4j.type.Encodable;
import com.serotonin.bacnet4j.type.enumerated.PropertyIdentifier;
import com.serotonin.bacnet4j.type.primitive.ObjectIdentifier;
import com.serotonin.bacnet4j.util.DiscoveryUtils;
import com.serotonin.bacnet4j.util.RequestUtils;

import java.util.List;


public class BACnetUtil {
    public static LocalDevice initLocalDevice(IpNetwork ipNetwork, int localDeviceNumber) throws Exception {
        System.out.println("************************** 初始化本地虚拟设备 " + localDeviceNumber + " ****************************");
        LocalDevice localDevice = new LocalDevice(localDeviceNumber, new DefaultTransport(ipNetwork));
        localDevice.initialize();
        localDevice.startRemoteDeviceDiscovery();
        return localDevice;
    }

    public static IpNetwork initIpNetwork(String ip, String subnet) {
        System.out.println("************************** 初始化网络信息 ****************************");
        IpNetworkBuilder ipNetworkBuilder = new IpNetworkBuilder()
                .withLocalBindAddress(ip)
                .withSubnet(subnet, 24)
                //Yabe默认的UDP端口
                .withPort(47808)
                .withBroadcast(IpUtil.getBroadcastByIpAndSubnet(ip, subnet), 24)
                .withReuseAddress(true);

        System.out.println("ip:        " + ip);
        System.out.println("subnet:    " + subnet);
        System.out.println("broadcast: " + IpUtil.getBroadcastByIpAndSubnet(ip, subnet));
        String networkSegment = IpUtil.getNetworkSegmentByIpAndSubnet(ip, subnet);
        System.out.println("所在网段:    " + networkSegment);

        return ipNetworkBuilder.build();
    }
}

